package net.vkits.controller;

import net.vkits.common.storage.StorageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.activation.MimetypesFileTypeMap;
import javax.annotation.Resource;
import java.io.File;

/**
 * Created by ethan-liu on 2016/11/18.
 */
@Controller
@RequestMapping("/files")
public class FilesController {
    private static final Logger logger = LoggerFactory.getLogger(FilesController.class);

    @Resource
    private StorageService storageService;

    @RequestMapping(value = "/{filename:.+}")
    @ResponseBody
    public ResponseEntity<org.springframework.core.io.Resource> serveFile(@PathVariable String filename) {
        org.springframework.core.io.Resource file = storageService.loadAsResource(filename);
        String contentType = new MimetypesFileTypeMap().getContentType(new File("/tmp/" + filename));
        logger.info("File content type is : " + contentType);
        return ResponseEntity
                .ok()
                .contentType(MediaType.parseMediaType(contentType))
                .body(file);
    }
}
